// src/store/modules/auth.js
import { defineStore } from 'pinia'
import { getCurrentUser, logout, refreshToken } from '@/api/auth'
import { getUserSubscriptions } from '@/api/vpn'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: localStorage.getItem('access_token') || null,
        user: null,
        userSubscriptions: [],
        currentSubscription: null,
        isAuthenticated: !!localStorage.getItem('access_token'),
        loading: false,
        initialized: false
    }),

    actions: {
        setToken(token) {
            this.token = token
            this.isAuthenticated = true
            localStorage.setItem('access_token', token)
        },

        async clearToken() {
            try {
                await logout()
            } catch (error) {
                console.error('退出登录失败:', error)
            } finally {
                this.token = null
                this.user = null
                this.userSubscriptions = []
                this.currentSubscription = null
                this.isAuthenticated = false
                this.initialized = false
                localStorage.removeItem('access_token')
            }
        },

        setUser(user) {
            this.user = user
        },

        setUserSubscriptions(subscriptions) {
            this.userSubscriptions = subscriptions
            // 设置当前活跃的订阅
            this.currentSubscription = subscriptions.find(sub => sub.is_active) || null
        },

        async fetchUserData() {
            if (!this.isAuthenticated) return

            this.loading = true
            try {
                // 获取用户信息
                const userResponse = await getCurrentUser()
                if (userResponse.data) {
                    this.setUser(userResponse.data)
                }

                // 获取用户订阅信息
                if (this.user) {
                    const subsResponse = await getUserSubscriptions(this.user.id)
                    this.setUserSubscriptions(subsResponse.data)
                }

                this.initialized = true
            } catch (error) {
                console.error('获取用户数据失败:', error)
                // 如果获取用户信息失败，清除token
                if (error.response?.status === 401) {
                    this.clearToken()
                }
                throw error
            } finally {
                this.loading = false
            }
        },

        updateCurrentSubscription(updatedSubscription) {
            const index = this.userSubscriptions.findIndex(sub => sub.id === updatedSubscription.id)
            if (index !== -1) {
                this.userSubscriptions[index] = updatedSubscription
                if (updatedSubscription.is_active) {
                    this.currentSubscription = updatedSubscription
                }
            }
        },

        // 验证token有效性
        validateToken() {
            const token = this.token
            // 简单的token验证：检查是否存在且长度合理
            if (!token || token.length < 10) {
                this.clearToken()
                return false
            }

            // 可以添加更复杂的token验证逻辑，比如检查过期时间
            try {
                // JWT token解析（如果使用JWT）
                const payload = JSON.parse(atob(token.split('.')[1]))
                const exp = payload.exp * 1000 // 转换为毫秒
                if (Date.now() >= exp) {
                    console.log('Token已过期')
                    this.clearToken()
                    return false
                }
                return true
            } catch (e) {
                // 如果不是JWT token，使用简单验证
                return true
            }
        },

        // 检查认证状态
        async checkAuth() {
            if (!this.validateToken()) {
                return false
            }

            try {
                await this.fetchUserData()
                return true
            } catch (error) {
                console.error('验证登录状态失败:', error)

                // 尝试刷新token（如果有refresh token）
                if (error.response?.status === 401) {
                    try {
                        await this.refreshAuthToken()
                        return true
                    } catch (refreshError) {
                        console.error('刷新token失败:', refreshError)
                        this.clearToken()
                        return false
                    }
                }

                this.clearToken()
                return false
            }
        },

        // 刷新认证token
        async refreshAuthToken() {
            try {
                const response = await refreshToken()
                if (response.data && response.data.access_token) {
                    this.setToken(response.data.access_token)
                    return true
                }
                return false
            } catch (error) {
                console.error('刷新token失败:', error)
                throw error
            }
        },

        // 初始化认证状态
        async initializeAuth() {
            if (this.initialized) return true

            if (this.isAuthenticated) {
                return await this.checkAuth()
            }

            this.initialized = true
            return false
        }
    },

    getters: {
        getToken: (state) => state.token,
        getUser: (state) => state.user,
        getUserSubscriptions: (state) => state.userSubscriptions,
        getCurrentSubscription: (state) => state.currentSubscription,
        getIsAuthenticated: (state) => state.isAuthenticated,
        hasActiveSubscription: (state) => !!state.currentSubscription,
        isLoading: (state) => state.loading,
        isInitialized: (state) => state.initialized
    }
})